<?php
/*
 *
----------------------------------------------------------------------------------------------------------------
一个简单的数据分页类 Author: Zhang Junlei (zhangjunlei26@gmail.com)
----------------------------------------------------------------------------------------------------------------
Useage:
$pager=Pagination_SQL::factory(array(
	'group'=>'recharge_history',//配置文件中的组
	'url'=>'/account/recharge_his/{page}/{total_items}',//分页后生成的地址，格式随意，预留{page}和{total_items}占位符
	'current_page'=>$_GET['arg1'],//当前页
	'items_per_page'=>10,//每页显示记录数
    'total_items'=>$_GET['arg2'],//总行数
    'sql'=>'SELECT * FROM `sys_countries`',
	'db'=>func::get_db(),
));
//取结果
$rs=$pager->fetch_result();
//取分页链接
$links=$pager->render('punbb');
echo $links;
----------------------------------------------------------------------------------------------------------------
 */
class Pagination_SQL extends Pagination
{

	protected $sql;

	protected $db;

	protected $result;

	protected $ori_current_page;

	/**
	 * 数据库分页
	 * 
	 * @param $db_or_sql mix
	 *       	 sql语句或经过prepare的Db对象
	 * @param $options array       	
	 */
	public function __construct ($options)
	{
		$this->setup_config($options);
		$this->total_items = (int) max(0, $options['total_items']);
		$this->items_per_page = (int) max(1, $this->items_per_page);
		$this->sql_offset = (int) ($this->current_page - 1) * $this->items_per_page;
		$this->result = $this->_fetch_result();
		if (! $this->total_items)
		{
			$this->mk_matches();
		}
		$this->initialize();
	}

	/**
	 * 返回当前查询的行数
	 */
	public function mk_matches ()
	{
		$sql = "SELECT FOUND_ROWS() LIMIT 1;";
		return $this->total_items = $this->db->query($sql);
	}

	public function fetch_result ()
	{
		return $this->result;
	}

	/**
	 * 取结果集
	 */
	protected function _fetch_result ($by_key = NULL)
	{
		$sql = (array) $this->sql;
		$this->sql_offset = (int) ($this->current_page - 1) * $this->items_per_page;
		$this->sql_limit = " LIMIT {$this->items_per_page} OFFSET {$this->sql_offset};";
		// 计算行数
		if (! $this->total_items)
		{
			$sql[0] = preg_replace('/^\s*SELECT/i', 'SELECT SQL_CALC_FOUND_ROWS', $sql[0]) . $this->sql_limit;
		}
		else
		{
			$sql[0] .= $this->sql_limit;
		}
		$_sql = $sql[0];
		array_shift($sql);
		$rs = $this->db->query($_sql, $sql);
		if ($rs && $by_key)
		{
			return Arr::byKey($rs, $by_key);
		}
		else
		{
			return $rs;
		}
	}
}
